<?php
/**
 * Created by PhpStorm.
 * User: lance
 * Date: 2017/10/31
 * Time: 16:07
 */

namespace app\manager\admin;

use app\common\builder\ZBuilder;
use app\common\log\addRole\ManagerAdd;
use app\common\log\createAccount\CreateManager;
use app\manager\model\Manager;
use think\Db;
use php_excel\libs\Excel;
use app\admin\controller\Admin;

/**
 * 客户经理导入，添加
 * Class Import
 * @package app\manager\admin
 */
class Import extends Admin
{
    /**
     * 导入客户经理日志:
     * @return mixed
     * @throws ManagerException
     */
    private $a_managerInfo;

    public function importManager()
    {
        if (request()->isAjax()):
            set_time_limit(0);
            $i_fileId = input('file');
            $s_path = 'public/' . Db::name('admin_attachment')->where('id', $i_fileId)->value('path');
            //step1 获取excel数据
            if (!is_file($s_path)):
                $this->error("请上传客户经理资料文件");
            endif;
            $o_excel = new Excel();
            $a_data = $o_excel->import($s_path);
            array_shift($a_data);//去除表头
            //step2 组织数据
            $a_info = config('manager_info');
            $a_fields = array_map(function ($a_item) {
                return $a_item[1];
            }, $a_info);
            //去除头
            array_shift($a_fields);
            //step3 插入数据与记录日志
            $o_cus = new Manager();
            $i_count = 0;

            $i_sucNum = 0;//正确处理的人数
            $i_failNum = 0;//错误处理的人数
            foreach ($a_data[0] as $i_key => $a_value):
                if (empty($a_value[2])):
                    continue;
                endif;
                $i_count++;
                try {
                    Db::startTrans();
                    //身份证位数科学计数法转换为字符串
                    if (strstr($a_value[4], 'E') && is_float($a_value[4])):
                        $a_value[4] = number_format($a_value[4], 0, '', '');
                    endif;
                    //新增客户经理
                    if (count($a_fields) !== count($a_value)):
                        $this->error("请按照上传文件内容格式上传正确的客户经理资料");
                    endif;
                    $a_data = array_combine($a_fields, $a_value);
                    //判断客户经理是否存在
                    $this->a_managerInfo = $a_data;
                    $a_tmp = $this->isExist();
                    $i_id = $a_tmp['id'];
                    if ($i_id):
                        if ($o_cus->where('id', $i_id)->field('number', true)->update() === false):
                            throw new ManagerException("更新第" . ($i_key + 1) . "个客户经理失败");
                        endif;
                    else:
                        if (!$o_cus->insert($a_data)):
                            throw new ManagerException("新增第" . ($i_key + 1) . "个客户经理失败");
                        endif;
                    endif;
                    if (!$i_id):
                        //分配客客户经理账号
                        $i_managerId = $o_cus->getLastInsID();
                        $a_data = [
                            'username' => $a_value[2],
                            'nickname' => $a_value[2],
                            'email' => $a_value[8],
                            //TODO 客户经理初始密码位身份证后六位
                            //password' => substr(input('cert_number'), -6),
                            'password' => 123456,
                            'mobile' => $a_value[6],
                            'role_id' => $i_managerId,
                            'status' => 1,
                            'role' => 3
                        ];
                        if (($s_msg = CreateManager::addOne($a_data)) !== true) :
                            throw new ManagerException($s_msg);
                        endif;
                    endif;
                    Db::commit();
                    //记录添加客户经理日志
                    $o_log = new ManagerAdd([
                        'role_id' => $i_id ?: $i_managerId,
                        'status' => 1,
                        'error' => '',
                        'update' => $i_id ? true : false,
                        'role_type' => 2,
                        'type' => 2,//批量导入
                        'content' => json_encode($a_data)
                    ]);
                    $o_log->addOne();
                    $i_sucNum++;
                } catch (ManagerException $e) {
                    Db::rollback();
                    $i_failNum++;
                    //记录错误日志
                    $o_log = new ManagerAdd([
                        'role_id' => 0,
                        'status' => 0,
                        'update' => $i_id ? true : false,
                        'error' => $e->getErrorMsg(),
                        'content' => json_encode($a_data),
                        'type' => 2,
                        'role_type' => 2,
                    ]);
                    $o_log->addOne();
                }
            endforeach;
            $this->success("此次操作共新增客户经理" . $i_count . "成功添加" . $i_sucNum . '位。失败添加' . $i_failNum . '位。具体可查看客户经理添加日志', null, '', 6);
        else:
            $s_tips = <<<EOT
1.支持导入格式xls,xlsx<br/>
2.客户经理资料顺序为，所属部门、姓名、帐号(柜员员)、所属网点、身份证号、性别、移动电话、办公电话、电子邮箱，不能缺少或者颠倒
EOT;

            return ZBuilder::make('form')
                ->setPageTips($s_tips)
                ->addFile('file', '客户经理资料文件', '仅支持xls,xlsx两种格式', '', '', 'xls,xlsx')
                ->fetch();
        endif;
    }

    public function add()
    {
        if (request()->isAjax()):
            $o_validate = Validate('Manager');
            $this->a_managerInfo = input('');
            $a_tmp = $this->isExist();
            if ($a_tmp):
                $this->error("柜员号：" . $a_tmp['number'] . '已经存在！');
            endif;
            //验证数据
            if ($o_validate->check(input('')) === FALSE):
                $this->error($o_validate->getError());
            endif;
            //保存数据
            $o_model = new Manager();
            Db::startTrans();
            try {
                //step1 添加客户经理
                if (!$o_model->insert(input(''))):
                    throw new ManagerException('添加失败！');
                endif;
                $i_managerId = $o_model->getLastInsID();
                //step2 分配客户经理账号
                $a_data = [
                    'username' => input('number'),
                    'nickname' => input('number'),
                    'email' => input('email'),
                    //TODO 客户经理初始密码位身份证后六位
                    //password' => substr(input('cert_number'), -6),
                    'password' => 123456,
                    'mobile' => input('tel_number'),
                    'role_id' => $i_managerId,
                    'status' => 1,
                    'role' => 3
                ];
                if (($s_msg = CreateManager::addOne($a_data)) !== true) :
                    throw new ManagerException($s_msg);
                endif;
                Db::commit();
                //step3 记录添加客户经理日志
                $o_log = new ManagerAdd([
                    'role_id' => $i_managerId,
                    'status' => 1,
                    'error' => '',
                    'role_type' => 2,
                    'content' => json_encode(input(''))
                ]);
                $o_log->addOne();
                $this->success("添加成功!");
            } catch (ManagerException $e) {
                Db::rollback();
                //记录错误日志
                $o_log = new ManagerAdd([
                    'role_id' => 0,
                    'status' => 0,
                    'error' => $e->getErrorMsg(),
                    'content' => json_encode(input('')),
                    'role_type' => 2,
                ]);
                $o_log->addOne();
                $this->error($e->getErrorMsg());
            }
        else:
            //提示信息
            $s_tips = <<<EOT
1.手动添加客户经理。<br/>
2.客户经理帐号为柜员号，初始密码为123456,登录后可修改。
EOT;

            return ZBuilder::make('form')
                ->addHidden('type', 0)
                ->setPageTips($s_tips)
                ->addFormItems(Config('manager_info'))
                ->fetch();
        endif;
    }

    /**
     * 根据柜员码判断好似否存在相同客户经理
     */
    private function isExist()
    {
        $s_certNumber = $this->a_managerInfo['number'];
        return Db::name('manager')->where('number', $s_certNumber)->field('id,number')->find();
    }
}